import winston from 'winston';

// 日志级别
const LOG_LEVELS = {
  error: 0,
  warn: 1,
  info: 2,
  debug: 3
};

class Logger {
  private static instance: Logger;
  private logger: winston.Logger;

  private constructor() {
    // 从环境变量中获取日志配置
    const level = process.env.LOG_LEVEL || 'info';
    const format = process.env.LOG_FORMAT || 'json';

    // 创建日志实例
    this.logger = winston.createLogger({
      level,
      levels: LOG_LEVELS,
      format: format === 'json' ? winston.format.json() : winston.format.simple(),
      transports: [
        new winston.transports.Console({
          format: winston.format.combine(
            winston.format.colorize(),
            winston.format.timestamp(),
            winston.format.printf((info) => {
              const { timestamp, level, message, ...meta } = info;
              return `${timestamp || new Date().toISOString()} [${level}]: ${message} ${Object.keys(meta).length ? JSON.stringify(meta) : ''}`;
            })
          )
        })
      ]
    });
  }

  public static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }

  public info(message: string, meta?: Record<string, unknown>): void {
    this.logger.info(message, meta);
  }

  public error(message: string, meta?: Record<string, unknown>): void {
    this.logger.error(message, meta);
  }

  public warn(message: string, meta?: Record<string, unknown>): void {
    this.logger.warn(message, meta);
  }

  public debug(message: string, meta?: Record<string, unknown>): void {
    this.logger.debug(message, meta);
  }
}

// 导出单例实例
export const logger = Logger.getInstance(); 